package com.sky.httpd;

import com.sky.templatehttpd.Response;
import com.sky.templatehttpd.Server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

class Main {

    private Main() {
    }
    /** Commons logger used for logging. */
    private static final Log LOG = LogFactory.getLog(Main.class);

    public static void main(String... args) throws IOException, InterruptedException {

        Server srv = new Server(8080) {

            @Override
            protected Response serve(String uri, String method, Properties header, Properties params) {
                LOG.debug(method + " '" + uri + "' ");

                StringBuilder responseContent = new StringBuilder();
                responseContent.append("<html><body>");
                responseContent.append(method).append(" '").append(uri).append("' ");
                responseContent.append("<ul>");
                Enumeration<?> propertieNames = header.propertyNames();
                while (propertieNames.hasMoreElements()) {
                    String propertyName = (String) propertieNames.nextElement();
                    String value = header.getProperty(propertyName);
                    LOG.debug("  HDR: '" + propertyName + "' = '" + value + "'");
                    responseContent.append("<li>HDR: '").append(propertyName).append("' = '").append(value).append("'");
                }
                responseContent.append("</ul><ul>");

                propertieNames = params.propertyNames();
                while (propertieNames.hasMoreElements()) {
                    String propertyName = (String) propertieNames.nextElement();
                    String value = params.getProperty(propertyName);
                    LOG.debug("  PRM: '" + propertyName + "' = '" + value + "'");
                    responseContent.append("<li>PRM: '").append(propertyName).append("' = '").append(value).append("'");
                }
                responseContent.append("</ul></body></html>");
                return new Response(Response.HTTP_OK, Response.MIME_HTML, responseContent.toString());
            }
        };

        srv.start();
        while (srv.isStarted()) {
            synchronized (srv) {
                srv.wait();
            }
        }
    }
}
